package com.xrkj.miniprogram.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

@SuppressWarnings("deprecation")
public class JwtUtil {

    private static final long EXPIRATION_TIME = 86400000; // 24 hours
    private static final String SECRET_KEY="1hnQLKKE7uAcNLKKh1MuQytJUjOzK+L+pF6i45nKgGg=";
    //生成token
    public static String generateToken(String openid) {
        Date now = new Date();
        Date expirationTime = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(openid)
                .setIssuedAt(now)
                .setExpiration(expirationTime)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    //校验token
	public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

	//从token中获取登录用户的openID
    public static String getUserOpenIDFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }
}
